<?php

namespace App\Console\Commands;

use App\Models\Agent;
use App\Models\ChatRecord;
use App\Models\ChatUnread;
use App\Models\User;
use App\Models\WxUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class SwooleServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:server';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole websocket';
    protected $redisClient;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //创建server
        $server = new \Swoole\WebSocket\Server("0.0.0.0", 9502);

        //心跳参数
        // $server->set([
        //     'heartbeat_check_interval' => 10,
        //     'heartbeat_idle_time' => 100,
        // ]);


        //连接成功回调
        $server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
            $this->info($request->fd . '链接成功');
            Redis::select(13);
        });

        //收到消息回调
        $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
            $data = json_decode($frame->data, true);
            var_dump($data);
            //用户刚连接的时候初始化，每个用户登录时记录该用户对应的fd
            if ($data['flag'] == 'init') {
                $id = decrypt($data['sendId']);
                Redis::set($id,$frame->fd);
                $logs = ChatUnread::where([
                    'status' => 0,
                    'rec_id' => $id,
                ])->get()->toArray();
                if($logs != null){
                    foreach ($logs as $value) {
                        $server->push($frame->fd, json_encode($value));
                    }
                    ChatUnread::where([
                        'rec_id' => $id,
                    ])->update(['status' => 1]);
                }
            }
            elseif ($data['flag'] == 'message') {
                $toFd = Redis::get($data['rec_id']);
                $fds = [];
                foreach ($server->connections as $fd) {
                    array_push($fds, $fd);
                }
                var_dump($fds);
                if (in_array($toFd, $fds)) {
                    $server->push($toFd, json_encode($data));
                } else {
                    $info['rec_id'] = $data['rec_id'];
                    $info['send_id'] = $data['send_id'];
                    $info['content'] = $data['content'];
                    $info['create_time'] = date('Y/m/d H:i:s');
                    $info['status'] = 0;
                    ChatUnread::create($info);
                }
            }
        });

        //关闭链接回调
        $server->on('close', function ($ser, $fd) {
            $this->info($fd . '断开链接');
        });

        $server->start();
    }
}
